class TagManager {
  // 初始化标签系统
  static init() {
      
  }
 // 添加这个缺失的方法
    static async loadTags() {
        const response = await fetch('data/tags.json');
        return await response.json();
    }
    // 增：添加新标签
    // 添加新标签（完整实现）
    static async addTag(imgName, newTag) {
         console.log(`尝试添加标签: ${imgName} -> ${newTag}`);
        try {
            const tagsData = await this.loadTags();
            
            // 深度拷贝避免污染原始数据
            const updatedData = JSON.parse(JSON.stringify(tagsData));
            
            if (updatedData[imgName]?.tags.includes(newTag)) {
                alert('该标签已存在！');
                return false;
            }
    
            if (!updatedData[imgName]) updatedData[imgName] = { tags: [] };
            updatedData[imgName].tags.push(newTag);
            updatedData[imgName].updated_at = new Date().toISOString();
    
            // 添加请求超时处理
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 5000);
            
            const response = await fetch('api/save_tags.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(updatedData),
                signal: controller.signal
            });
            
            clearTimeout(timeoutId);
            
            if (!response.ok) {
                throw new Error(`HTTP错误! 状态码: ${response.status}`);
            }
            
            const result = await response.json();
            if (!result.success) {
                throw new Error('后端返回失败');
            }
            
            // 更新本地显示
            const tagsContainer = document.querySelector(`#tags-${imgName.replace('.', '-')}`);
            if (tagsContainer) {
                const tagElement = document.createElement('span');
                tagElement.className = 'tag';
                tagElement.textContent = newTag;
                tagsContainer.appendChild(tagElement);
            }
            
            return true;
        } catch (error) {
            console.error('添加标签失败:', error);
            alert(`添加标签失败: ${error.message}`);
            return false;
        }
    }
    
    static async saveTags(data) {
        console.log("saveTags")
        try {
            const response = await fetch('api/save_tags.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });
            return response.ok;
        } catch (error) {
            console.error('保存失败:', error);
            return false;
        }
    }
    static async getTagsForImage(imgName) {
        const data = await this.loadTags();
        return data[imgName]?.tags || [];
    }
    
    static async updateSingleTag(imgName, oldTag, newTag) {
        const data = await this.loadTags();
        const index = data[imgName].tags.indexOf(oldTag);
        if (index !== -1) {
            data[imgName].tags[index] = newTag;
            return this.saveTags(data);
        }
        return false;
    }
  // 删：删除标签
  static deleteTag(imgName, targetTag) {
    /* 预留实现位 */
  }

  // 改：修改标签
  static updateTag(imgName, oldTag, newTag) {
    /* 预留实现位 */
  }

  // 查：搜索标签
  static searchByTag(keyword) {
    /* 预留实现位 */
  }
  

}

function bindAddTagEvents() {
    console.log("bindAddTagEvents")
    document.querySelectorAll('.add-tag-btn').forEach(btn => {
        btn.addEventListener('click', async () => {
            const imgName = btn.dataset.img;
            const input = btn.previousElementSibling;
            const newTag = input.value.trim();

            if (newTag) {
                await TagManager.addTag(imgName, newTag);
                input.value = ''; // 清空输入框
            }
        });
    });
}

//标签修改及删除功能--------------------------------------------------------------------------------------------------------
// 全局状态记录
let currentEditState = {
    imgName: null,
    oldTag: null,
    tagIndex: null
};

// 初始化标签编辑功能
function initTagEdit() {
    // 事件委托处理标签点击
    document.addEventListener('click', (e) => {
        if (e.target.classList.contains('tag')) {
            openEditModal(e.target);
        }
    });

    // 绑定模态框按钮
    document.getElementById('tag-update-btn').addEventListener('click', updateTag);
    document.getElementById('tag-delete-btn').addEventListener('click', deleteTag);
    document.getElementById('tag-cancel-btn').addEventListener('click', closeModal);
    document.getElementById('modal-overlay').addEventListener('click', closeModal);
}

// 打开编辑模态框
function openEditModal(tagElement) {
    const tagsContainer = tagElement.parentElement;
    const imgName = tagsContainer.id.replace('tags-', '').replace('-', '.');
    const tagIndex = Array.from(tagsContainer.children).indexOf(tagElement);
    
    currentEditState = {
        imgName,
        oldTag: tagElement.textContent,
        tagIndex
    };

    document.getElementById('tag-edit-input').value = currentEditState.oldTag;
    document.getElementById('edit-modal').style.display = 'block';
    document.getElementById('modal-overlay').style.display = 'block';
}

// 关闭模态框
function closeModal() {
    document.getElementById('edit-modal').style.display = 'none';
    document.getElementById('modal-overlay').style.display = 'none';
}

// 更新标签
async function updateTag() {
    const newTag = document.getElementById('tag-edit-input').value.trim();
    if (!newTag) return alert('标签不能为空');

    const { imgName, oldTag, tagIndex } = currentEditState;
    const tagsData = await TagManager.loadTags();
    
    // 更新数据
    tagsData[imgName].tags[tagIndex] = newTag;
    const success = await TagManager.saveTags(tagsData);
    
    if (success) {
        const tagsContainer = document.getElementById(`tags-${imgName.replace('.', '-')}`);
        tagsContainer.children[tagIndex].textContent = newTag;
        closeModal();
    }
}

// 删除标签
async function deleteTag() {
    const { imgName, tagIndex } = currentEditState;
    const tagsData = await TagManager.loadTags();
    
    // 删除数据
    tagsData[imgName].tags.splice(tagIndex, 1);
    const success = await TagManager.saveTags(tagsData);
    
    if (success) {
        const tagsContainer = document.getElementById(`tags-${imgName.replace('.', '-')}`);
        tagsContainer.children[tagIndex].remove();
        closeModal();
    }
}


//搜索框逻辑内容---------------------------------------------------------------------------------------------------
// 全局变量存储所有图片数据
let allImages = [];

// 初始化搜索功能
function initSearch() {
    const searchBtn = document.getElementById('search-btn');
    const resetBtn = document.getElementById('reset-btn');
    
    searchBtn.addEventListener('click', performSearch);
    resetBtn.addEventListener('click', resetSearch);
    
    // 回车键触发搜索
    document.getElementById('search-input').addEventListener('keypress', (e) => {
        if (e.key === 'Enter') performSearch();
    });
}

// 使用防抖减少频繁搜索
let searchTimer;
// 执行搜索
async function performSearch() {
    document.getElementById('search-btn').classList.add('loading');
    clearTimeout(searchTimer);
    searchTimer = setTimeout(async () => {
        const keyword = document.getElementById('search-input').value.trim();
        const container = document.getElementById('gallery-container');
        
        if (!keyword) {
            // 搜索为空时恢复原始分页
            currentPage = 1;
            await renderGallery(currentPage);
            return;
        }
        
        try {
            // 获取所有匹配的图片
            const response = await fetch(`api/search.php?q=${encodeURIComponent(keyword)}`);
            const matchedImages = await response.json();
            
            // 保存搜索结果到全局变量
            window.searchResults = matchedImages;
            totalImages = matchedImages.length;
            
            // 重置到第一页并渲染
            currentPage = 1;
            renderSearchResults(currentPage, matchedImages);
            document.getElementById('search-btn').classList.remove('loading');
            
        } catch (error) {
            console.error('搜索失败:', error);
        }
    }, 300);
}
// async function performSearch() {
//     clearTimeout(searchTimer);
//     searchTimer = setTimeout(async () => {  // 添加 async 关键字
//         const keyword = document.getElementById('search-input').value.trim();
//         if (!keyword) return;
        
//         try {
//             const response = await fetch(`api/search.php?q=${encodeURIComponent(keyword)}`);
//             const matchedImages = await response.json();
            
//             document.querySelectorAll('.image-container').forEach(el => {
//                 const imgName = el.querySelector('img').src.split('/').pop();
//                 el.style.display = matchedImages.includes(imgName) ? 'block' : 'none';
//             });
//         } catch (error) {
//             console.error('搜索失败:', error);
//         }
//     }, 300);
// }
// 新增：渲染搜索结果
function renderSearchResults(page, matchedImages) {
    const container = document.getElementById('gallery-container');
    container.innerHTML = '';
    
    // 计算当前页的数据范围
    const start = (page - 1) * perPage;
    const end = Math.min(start + perPage, matchedImages.length);
    const pageImages = matchedImages.slice(start, end);
    
    // 渲染当前页结果
    pageImages.forEach(imgName => {
        renderImageItem(imgName, container);
    });
    
    // 更新分页UI（使用匹配结果总数）
    updatePagination(page, matchedImages.length);
}

// 重置搜索
function resetSearch() {
    document.getElementById('search-input').value = '';
    window.searchResults = null; // 清除搜索缓存
    currentPage = 1;
    renderGallery(currentPage); // 重新加载原始分页
}

// // 修改renderGallery函数（开头添加）
// async function renderGallery() {
//     const [images, tags] = await Promise.all([
//         fetch('get_images.php').then(r => r.json()),
//         loadTags()
//     ]);
//     allImages = images; // 存储全局引用
//     console.log(allImages);
// }
// 新版渲染函数
async function renderGallery(page = 1) {
    const [allImages, tags] = await Promise.all([
        fetch('get_images.php').then(r => r.json()),
        loadTags()
    ]);
    
    allTags = tags;
    totalImages = allImages.length;
    const container = document.getElementById('gallery-container');
    container.innerHTML = '';
    
    // 计算当前页的图片范围
    const start = (page - 1) * perPage;
    const end = Math.min(start + perPage, totalImages);
    const pageImages = allImages.slice(start, end);
    
    // 渲染当前页图片
    pageImages.forEach(imgName => {
        renderImageItem(imgName, container);
    });
    
    // 更新分页UI
    updatePagination(page);
    
    // 绑定事件
    if (typeof bindAddTagEvents === 'function') {
        bindAddTagEvents();
    }
}



//全屏预览控制------------------------------------------------------------------------------------------------------
// 全屏预览控制
function initFullscreenPreview() {
    const overlay = document.getElementById('fullscreen-overlay');
    const fullscreenImg = document.getElementById('fullscreen-image');
    
    // 点击图片进入全屏
    document.addEventListener('click', (e) => {
        if (e.target.classList.contains('image-container') || 
            e.target.tagName === 'IMG' && e.target.closest('.image-container')) {
            
            const imgSrc = e.target.tagName === 'IMG' 
                ? e.target.src 
                : e.target.querySelector('img').src;
            
            openFullscreen(imgSrc);
        }
    });
    
    // 点击空白处退出
    overlay.addEventListener('click', closeFullscreen);
    overlay.addEventListener('touchend', closeFullscreen);//增加触摸控制
    // ESC键退出
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && overlay.style.display !== 'none') {
            closeFullscreen();
        }
    });
    
    // 增加长按触发标签编辑
    document.addEventListener('touchstart', (e) => {
        if(e.target.classList.contains('tag')) {
            this.longPressTimer = setTimeout(() => {
                openEditModal(e.target);
            }, 800); // 800ms长按
        }
    }, {passive: true});

    document.addEventListener('touchend', (e) => {
        clearTimeout(this.longPressTimer);
    }, {passive: true});
}

//图片自适应
function adjustFullscreenImage() {
    const img = document.getElementById('fullscreen-image');
    if (img.src) {
        const imgObj = new Image();
        imgObj.src = img.src;
        
        imgObj.onload = () => {
            const windowRatio = window.innerWidth / window.innerHeight;
            const imgRatio = imgObj.width / imgObj.height;
            
            if (imgRatio > windowRatio) {
                img.style.width = '90vw';
                img.style.height = 'auto';
            } else {
                img.style.height = '90vh';
                img.style.width = 'auto';
            }
        };
    }
}
// 监听窗口变化
window.addEventListener('resize', adjustFullscreenImage);
// 打开全屏
function openFullscreen(imgSrc) {
    const overlay = document.getElementById('fullscreen-overlay');
    const fullscreenImg = document.getElementById('fullscreen-image');
    
    fullscreenImg.src = imgSrc;
    overlay.style.display = 'block';
    
    // 强制重绘触发动画
    setTimeout(() => {
        overlay.classList.add('active');
    }, 10);
    
    // 禁用滚动
    document.body.style.overflow = 'hidden';
    //增加图片自适应
    adjustFullscreenImage();
    
     // 添加双指缩放
    let initialDistance = null;
    fullscreenImg.addEventListener('touchmove', (e) => {
        if(e.touches.length === 2) {
            const dist = Math.hypot(
                e.touches[0].clientX - e.touches[1].clientX,
                e.touches[0].clientY - e.touches[1].clientY
            );
            
            if(!initialDistance) initialDistance = dist;
            const scale = dist / initialDistance;
            fullscreenImg.style.transform = `scale(${scale})`;
        }
    }, {passive: false});

    fullscreenImg.addEventListener('touchend', () => {
        initialDistance = null;
    });
}

// 关闭全屏
function closeFullscreen() {
    const overlay = document.getElementById('fullscreen-overlay');
    
    overlay.classList.remove('active');
    setTimeout(() => {
        overlay.style.display = 'none';
        document.body.style.overflow = '';
    }, 300);
}

//下方翻页按钮相关------------------------------------------------------------------------------------------------
// 全局变量
let currentPage = 1;
const perPage = 15;
let totalImages = 0;

// 更新分页控件
function updatePagination(currentPage, totalItems = totalImages) {
    const totalPages = Math.ceil(totalItems / perPage);
    const pageNumbers = document.getElementById('page-numbers');
    pageNumbers.innerHTML = '';
    
    // 生成页码按钮（逻辑保持不变，但基于新的totalItems）
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, currentPage + 2);
    
    if (endPage - startPage < 4 && totalPages > 5) {
        if (currentPage < 3) endPage = Math.min(5, totalPages);
        if (currentPage > totalPages - 2) startPage = Math.max(1, totalPages - 4);
    }
    
    for (let i = startPage; i <= endPage; i++) {
        const btn = document.createElement('button');
        btn.textContent = i;
        if (i === currentPage) btn.classList.add('active');
        btn.addEventListener('click', () => {
            if (window.searchResults) {
                renderSearchResults(i, window.searchResults);
            } else {
                renderGallery(i);
            }
        });
        pageNumbers.appendChild(btn);
    }
    
    // 更新翻页按钮
    document.getElementById('page-prev').onclick = () => {
        if (currentPage > 1) {
            window.searchResults 
                ? renderSearchResults(currentPage - 1, window.searchResults)
                : renderGallery(currentPage - 1);
        }
    };
    
    document.getElementById('page-next').onclick = () => {
        if (currentPage < totalPages) {
            window.searchResults 
                ? renderSearchResults(currentPage + 1, window.searchResults)
                : renderGallery(currentPage + 1);
        }
    };
    
    document.getElementById('page-prev').disabled = currentPage === 1;
    document.getElementById('page-next').disabled = currentPage === totalPages;
}
// function updatePagination(currentPage) {
//     const totalPages = Math.ceil(totalImages / perPage);
//     const pageNumbers = document.getElementById('page-numbers');
//     pageNumbers.innerHTML = '';
    
//     // 计算显示的页码范围（始终保持5个按钮，当前页在中间）
//     let startPage = Math.max(1, currentPage - 2);
//     let endPage = Math.min(totalPages, currentPage + 2);
    
//     // 调整显示范围确保始终显示5个页码（如果总页数足够）
//     if (endPage - startPage < 4 && totalPages > 5) {
//         if (currentPage < 3) endPage = Math.min(5, totalPages);
//         if (currentPage > totalPages - 2) startPage = Math.max(1, totalPages - 4);
//     }
    
//     // 生成页码按钮
//     for (let i = startPage; i <= endPage; i++) {
//         const btn = document.createElement('button');
//         btn.textContent = i;
//         if (i === currentPage) btn.classList.add('active');
//         btn.addEventListener('click', () => {
//             renderGallery(i);
//         });
//         pageNumbers.appendChild(btn);
//     }
    
//     // 更新前后按钮状态
//     document.getElementById('page-prev').disabled = currentPage === 1;
//     document.getElementById('page-next').disabled = currentPage === totalPages;
    
//     // 绑定翻页事件
//     document.getElementById('page-prev').onclick = () => {
//         if (currentPage > 1) renderGallery(currentPage - 1);
//     };
//     document.getElementById('page-next').onclick = () => {
//         if (currentPage < totalPages) renderGallery(currentPage + 1);
//     };
// }
// 修改window.onload
window.onload = () => renderGallery(1);


// 然后绑定事件（确保在DOM加载后）
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM已加载，正在绑定事件');
    renderGallery();
    bindAddTagEvents();
    initTagEdit();
    initSearch();
    initFullscreenPreview();
});
        
// 调试输出放在类定义之后
console.log('TagManager 状态:', typeof TagManager);